package psi.springapp.mvc.service;

import model.Voter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import model.Party;
import psi.springapp.mvc.repositories.UserRepository;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IDEA.
 * Voter: Ѱ
 * Date: 05.10.14
 * Time: 10:29
 */
@Service
public class UserService {
    @Autowired
    UserRepository userRepository;

    public UserService() {
    }

    public void saveUser(Voter voter) {
        userRepository.save(voter);

    }

    public void voteParty(Voter voter, Party party) {
        if (!voter.isVoted()) {
            party.setVotesNumb(party.getVotesNumb() + 1);
            voter.setIdPartyVoted(party.getId_party());
            voter.setVoted(true);
        }

    }

    public Iterable<Voter> userAll() {
        return userRepository.findAll();
    }

    public void deleteAll() {
        userRepository.deleteAll();
    }

    public List<Voter> userList() {
        List<Voter> voters = new LinkedList<Voter>();
        Iterator i = userAll().iterator();
        Voter tmp;
        while (i.hasNext()) {
            tmp = (Voter) i.next();
            voters.add(tmp);
        }
        return voters;
    }

    public Voter getById(int id) {
        return userRepository.findOne(id);
    }


}
